package com.platform.controller;

import com.platform.util.CheckSignatureUtil;
import com.platform.util.MessageUtil;
import com.platform.util.XmlUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Logger;

/*
* 用户关注事件
* @Author:易鑫
* */
@RestController
@RequestMapping("/mp/attention")
public class MpController {
    Logger logger = Logger.getLogger(MpController.class.getName());
    /**
     *
     * @param request 请求
     * @param response 回复
     * @return 验证消息的确来自微信服务器
     */
    @RequestMapping(value = "/wechatMessage", method = RequestMethod.GET)
    @ResponseBody
    public String getMthodHandler(HttpServletRequest request, HttpServletResponse response){
        logger.info("进wechatMessage Get");
        try {
//            logger.info("aaa");
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (!StringUtils.isEmpty(signature) && !StringUtils.isEmpty(nonce) && !StringUtils.isEmpty(timestamp) &&
                    CheckSignatureUtil.checkSignature(signature, timestamp, nonce)) {
                return echostr;
            }else{
                return "fail";
            }
        } catch (Exception e) {
            return "fail";
        }
    }


    /**
     * [接受消息,并返回消息]
     * @param request 请求
     * @param response 回复
     */
    @RequestMapping(value = "/wechatMessage", method = RequestMethod.POST)
    public void postMthodHandler(HttpServletRequest request, HttpServletResponse response){
        logger.info("进wechatMessage Post");
        String message = "success";
        PrintWriter out = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            //把微信返回的xml信息转义成map
            Map<String, String> map = XmlUtil.xmlToMap(request);
            logger.info("weChatMap【1】:"+map);
            String fromUserName = map.get("FromUserName");//消息来源用户标识
            String toUserName = map.get("ToUserName");//消息目的用户标识
            String msgType = map.get("MsgType");//消息类型
            String content = map.get("Content");//消息内容

            String eventType = map.get("Event");
            if(MessageUtil.MSGTYPE_EVENT.equals(msgType)){//如果为事件类型
                if(MessageUtil.MESSAGE_SUBSCIBE.equals(eventType)){//处理订阅事件
                    logger.info("进wechatMessage Post订阅");
                    message = MessageUtil.subscribeForText(toUserName, fromUserName);
                }else if(MessageUtil.MESSAGE_UNSUBSCIBE.equals(eventType)){//处理取消订阅事件
                    logger.info("进wechatMessage Post取消订阅");
                    message = MessageUtil.unsubscribe(toUserName, fromUserName);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            out.println(message);
            if(out!=null){
                out.close();
            }
        }
    }

}
